package uploadfiletoserver;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ServerCheck implements Runnable{
    private Server server;

    public ServerCheck(Server server) {
        this.server = server;
    }

    @Override
    public void run() {
        boolean isOnline = isServerOnline(server);
        System.out.println("服务器" + server.getAddress() + "状态正常");
        //向服务器发送文件
        if (isOnline) {
            ExecutorService service = Executors.newFixedThreadPool(5);
            for (String file : server.getFileToSend()) {
                service.execute(new FileSend(server,file));
            }
            service.shutdown();
        }else {
            System.out.println("状态异常" + server.getAddress());
        }
    }
    private boolean isServerOnline(Server server) {
        // 检测服务器状态
        try {
            InetAddress address = InetAddress.getByName(server.getAddress());
            if(address.isReachable(500)){
                FTPClient ftpClient = new FTPClient();
                ftpClient.connect(server.getAddress(),server.getPort());
                //获取状态码
                int replyCode = ftpClient.getReplyCode();
                System.out.println(replyCode);
                if(FTPReply.isPositiveCompletion(replyCode)){
                    return true;
                }
            }
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return false;
    }
}
